import { Suspense } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import routes from "./routes"
import Loading from '@/components/Loading'
import useRouterInfo from './useRouterInfo'

const Element = function Element({ item }) {
    let { redirect, component: Component, meta } = item
    /* 重定向的处理 */
    if (redirect) return <Navigate to={redirect} />
    /* 正常渲染组件 */
    // @1 修改页面的标题
    let title = meta?.title
    document.title = title ? `${title} - OA管理系统` : `OA管理系统`

    // @2 把路由跳转和解析的内容，作为属性传递给组件
    const attrs = useRouterInfo()

    return <Suspense fallback={<Loading />}>
        <Component {...attrs} />
    </Suspense>
}

const createRouteList = function createRouteList(routes) {
    if (!Array.isArray(routes)) return null
    return <>
        {routes.map((item, index) => {
            let { path, children } = item
            return <Route
                key={index}
                path={path}
                element={<Element item={item} />}>
                {/* 基于递归渲染子级路由 */}
                {children ? createRouteList(children) : null}
            </Route>
        })}
    </>
}

export default function RouterView() {
    return <Routes>
        {createRouteList(routes)}
    </Routes>
}